﻿using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using TYStudioDemo.Interfaces;
using TYStudioDemo.Commons;

namespace TYStudioDemo.Services
{
    public class TYExceptionService : ITYExceptionService
    {
        public string HandleException(Exception exception, Dictionary<string, object> parms, string message)
        {
            //穿件我们自己定义的异常类
            TYException tyException = new TYException(message, exception);

            //建立一个StackFrame
            StackFrame frame = new StackFrame(1, true);

            //记录抛出异常的文件名，方法名和，行号
            tyException.SetErrorProperty(TYException.CurrentFilename, frame.GetFileName());
            tyException.SetErrorProperty(TYException.CurrentFunction, frame.GetMethod().Name);
            tyException.SetErrorProperty(TYException.CurrentLineNumber, frame.GetFileLineNumber().ToString());
            // parameters, if present
            if (parms != null)
            {
                foreach (KeyValuePair<string, object> parm in parms)
                {
                    if (parm.Value != null)
                    {
                        tyException.SetErrorProperty(parm.Key, parm.Value.ToString());
                    }
                }
            }

            //使用EntityPrise Library记录异常信息，TYStudioPolicy配置在Web.Config文件中
            ExceptionPolicy.HandleException(tyException, "TYStudioPolicy");

            //返回有好的错误信息到页面
            return tyException.Message;
        }
    }
}
